package com.shenma2009.utils;

import java.util.Random;

/**
 * @author 12692
 * @version 1.0
 * @description: 随机字符串工具类
 * @date 2022/1/23 21:09
 */

public class RandomUtils {

    public static RandomUtils random() {
        return new RandomUtils();
    }

    /**
     * @description 获取定长随机数字字符串
     * @author 12692
     * @date 2022/1/12 10:56
     * @version 1.0
     */
    public String randomIntCode(int length) {
        String code = "";
        Random random = new Random();
        while (true) {
            if(code.length()>=length) {
                break;
            }
            int i = random.nextInt(9);
            // 排除0开头的数字
            if(i == 0 && code.length() == 0) {
                continue;
            }
            code = code + i;
        }

        return code;
    }

    /**
     * @description 产生字母验证码
     * @author 12692
     * @date 2022/1/12 12:27
     * @version 1.0
     */
    public String randomLetterCode(int length) {
        String letters = "abcdefghijkmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
        Random random = new Random();

        String code = "";

        while (true) {
            if(code.length()>=length) {
                break;
            }
            int index = random.nextInt(letters.length()-1);

            code = code + letters.charAt(index);
        }

        return code;
    }

    /**
     * @description 根据字符库生成随机字符串验证码
     * @author 12692
     * @date 2022/1/12 12:32
     * @version 1.0
     */
    public String randomCode(String letters, int length) {
        Random random = new Random();

        String code = "";

        while (true) {
            if(code.length()>=length) {
                break;
            }
            int index = random.nextInt(letters.length()-1);

            code = code + letters.charAt(index);
        }

        return code;
    }
}
